package com.xc.erp.modules.erp.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.xc.erp.common.utils.ConstantOssPropertiesUtils;
import com.xc.erp.modules.erp.service.FileService;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * OSS
 *
 * @author wjw 2022/12/14
 * @DateTime: 2022/12/14 15:24
 */
@Service
public class FileServiceImpl implements FileService {

    @Override
    public String upload(MultipartFile file) {
        String endpoint = ConstantOssPropertiesUtils.EDNPOINT;
        String accessKeyId = ConstantOssPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantOssPropertiesUtils.SECRECT;
        String bucketName = ConstantOssPropertiesUtils.BUCKET;
        OSS ossClient = null;
        InputStream inputStream = null;
        try {
            InputStream stream = file.getInputStream();
            //获取实际的名称
            String filename = file.getOriginalFilename();

            //生成一个随机唯一的值，使用UUID,添加到文件名称里面
            String uuid = UUID.randomUUID().toString().replace("-", " ");

            filename = uuid + filename;

            //按照当前日期，创建文件夹，上传到文件夹里面
            String timeUrl = new DateTime().toString("yyyy/MM/dd");

            filename = timeUrl + "/" + filename;

            //创建OSSClient实例
            ossClient = new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);

            //调用方法实现上传
            ossClient.putObject(bucketName,filename,inputStream);

            //关闭OSSClient
            ossClient.shutdown();

            //返回上传的路径
            return "https://" + bucketName + "." + endpoint + "/" + filename;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

}
